package info.jafe.common.task;

import android.support.annotation.UiThread;

/**
 * Created by jafe chang on 2016/12/30.
 */

public abstract class ManagedTask implements Runnable {
    private Object[] params;

    public ManagedTask() {
    }

    public ManagedTask(Object... params) {
        this.params = params;
    }

    final void setParams(Object[] params) {
        this.params = params;
    }

    protected abstract Object[] task(Object... params);

    @UiThread
    protected void onSuccess() {
    }

    @UiThread
    protected void onSuccess(Object[] results) {
    }

    @UiThread
    protected void onFailed() {
    }

    @Override
    public final void run() {
        try {
            final Object[] results = task(params);

            if (results == null) {
                TaskManager.post(new Runnable() {
                    @Override
                    public void run() {
                        onSuccess();
                    }
                });
            } else {
                TaskManager.post(new Runnable() {
                    @Override
                    public void run() {
                        onSuccess(results);
                    }
                });
            }


        } catch (Exception e) {
            TaskManager.post(new Runnable() {
                @Override
                public void run() {
                    onFailed();
                }
            });
        }
    }
}
